# 创建票房分析组件
<template>
  <div class="box-office-analysis">
    <el-card class="analysis-card">
      <template #header>
        <div class="card-header">
          <span>票房分析</span>
          <div class="header-right">
            <el-radio-group v-model="analysisType" size="small">
              <el-radio-button label="rank">票房排名</el-radio-button>
              <el-radio-button label="trend">票房趋势</el-radio-button>
              <el-radio-button label="proportion">票房占比</el-radio-button>
              <el-radio-button label="split">分账比例</el-radio-button>
            </el-radio-group>
            <el-button type="primary" size="small" @click="loadData">
              <el-icon><Refresh /></el-icon>刷新数据
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 图表容器 -->
      <div class="chart-container" ref="chartRef"></div>
      
      <!-- 分析总结 -->
      <div class="analysis-summary">
        <h3>分析总结</h3>
        <div class="summary-content" v-if="tableData.length">
          <template v-if="analysisType === 'rank'">
            <p>当前共有 {{ movieCount }} 部电影上映，总票房达 {{ formatNumber(totalBoxOffice) }} 万元。其中：</p>
            <ul>
              <li>票房冠军《{{ topMovie?.movie_name }}》以 {{ formatNumber(topMovie?.sum_box_desc) }} 万的成绩领跑</li>
              <li>前三名电影票房占比达 {{ top3Concentration.toFixed(2) }}%，市场集中度{{ top3Concentration > 60 ? '较高' : '适中' }}</li>
              <li>排名前十的电影中，{{ getTop10Analysis() }}</li>
            </ul>
          </template>

          <template v-if="analysisType === 'trend'">
            <p>票房走势分析显示：</p>
            <ul>
              <li>{{ getTrendAnalysis() }}</li>
              <li>环比增长率为 {{ boxOfficeGrowth > 0 ? '+' : '' }}{{ boxOfficeGrowth.toFixed(2) }}%，市场表现{{ getGrowthComment() }}</li>
              <li>近期票房走势{{ getTrendComment() }}</li>
            </ul>
          </template>

          <template v-if="analysisType === 'proportion'">
            <p>票房市场份额分析：</p>
            <ul>
              <li>前八大电影占据了总票房的 {{ getTop8Proportion().toFixed(2) }}%</li>
              <li>头部电影《{{ topMovie?.movie_name }}》市场份额为 {{ getTopMovieShare().toFixed(2) }}%</li>
              <li>市场竞争格局{{ getMarketCompetition() }}</li>
            </ul>
          </template>

          <template v-if="analysisType === 'split'">
            <p>分账比例分析结果：</p>
            <ul>
              <li>平均分账比例为 {{ (avgSplitRate * 100).toFixed(2) }}%，{{ getSplitRateComment() }}</li>
              <li>分账比例分布：{{ splitRateDistribution }}</li>
              <li>最高分账比例：《{{ topSplitMovie?.movie_name }}》达 {{ ((topSplitMovie?.split_box_rate || 0) * 100).toFixed(2) }}%</li>
            </ul>
          </template>
        </div>
        <el-empty v-else description="暂无数据可供分析" />
      </div>
      
      <!-- 数据表格 -->
      <el-table
        :data="paginatedData"
        style="width: 100%; margin-top: 20px;"
        :height="300"
        stripe
        border
        highlight-current-row
      >
        <el-table-column prop="movie_name" label="电影名称" min-width="120" />
        <el-table-column label="累计票房" min-width="120" sortable>
          <template #default="{ row }">
            {{ formatNumber(row.sum_box_desc) }}万
          </template>
        </el-table-column>
        <el-table-column label="分账票房比例" min-width="120" sortable>
          <template #default="{ row }">
            <el-progress 
              :percentage="row.split_box_rate * 100" 
              :format="(val) => val.toFixed(2) + '%'"
              :color="getProgressColor(row.split_box_rate)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="release_info" label="上映信息" min-width="120" />
        <el-table-column prop="updated_at" label="更新时间" min-width="160" />
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="tableData.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { getMovies } from '@/api/movie'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'

const analysisType = ref('rank')
const chartRef = ref(null)
const chart = ref(null)
const tableData = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 计算总票房
const totalBoxOffice = computed(() => {
  return tableData.value.reduce((sum, movie) => sum + movie.sum_box_desc, 0)
})

// 计算电影数量
const movieCount = computed(() => tableData.value.length)

// 计算平均分账比例
const avgSplitRate = computed(() => {
  if (!tableData.value.length) return 0
  return tableData.value.reduce((sum, movie) => sum + movie.split_box_rate, 0) / tableData.value.length
})

// 获取票房最高的电影
const topMovie = computed(() => {
  return tableData.value[0] || null
})

// 获取分账比例最高的电影
const topSplitMovie = computed(() => {
  return [...tableData.value].sort((a, b) => b.split_box_rate - a.split_box_rate)[0] || null
})

// 计算前三名票房集中度
const top3Concentration = computed(() => {
  if (!tableData.value.length || !totalBoxOffice.value) return 0
  const top3Sum = tableData.value.slice(0, 3).reduce((sum, movie) => sum + movie.sum_box_desc, 0)
  return (top3Sum / totalBoxOffice.value) * 100
})

// 计算分账比例分布描述
const splitRateDistribution = computed(() => {
  const total = tableData.value.length
  if (!total) return '暂无数据'
  
  const high = tableData.value.filter(m => m.split_box_rate >= 0.8).length
  const medium = tableData.value.filter(m => m.split_box_rate >= 0.5 && m.split_box_rate < 0.8).length
  const low = total - high - medium
  
  return `高(≥80%): ${high}部, 中(50-80%): ${medium}部, 低(<50%): ${low}部`
})

// 模拟票房增长率（实际项目中应从后端获取）
const boxOfficeGrowth = ref(12.5)

// 分析辅助函数
const getTop10Analysis = () => {
  const top10 = tableData.value.slice(0, 10)
  const avgBoxOffice = top10.reduce((sum, movie) => sum + movie.sum_box_desc, 0) / 10
  const aboveAvg = top10.filter(movie => movie.sum_box_desc > avgBoxOffice).length
  return `平均票房 ${formatNumber(avgBoxOffice)} 万，其中 ${aboveAvg} 部影片超过平均水平`
}

const getTrendAnalysis = () => {
  // 这里可以根据实际数据计算趋势
  const isRising = boxOfficeGrowth.value > 0
  return isRising ? 
    '整体呈上升趋势，市场表现活跃' : 
    '整体呈下降趋势，市场需要新作品提振'
}

const getGrowthComment = () => {
  if (boxOfficeGrowth.value > 20) return '表现优异'
  if (boxOfficeGrowth.value > 0) return '稳定增长'
  if (boxOfficeGrowth.value > -10) return '略有下滑'
  return '需要关注'
}

const getTrendComment = () => {
  // 这里可以根据实际数据分析近期趋势
  return boxOfficeGrowth.value > 0 ? '呈现上升态势，市场活力充足' : '有所回落，建议关注新片表现'
}

const getTop8Proportion = () => {
  if (!tableData.value.length || !totalBoxOffice.value) return 0
  const top8Sum = tableData.value.slice(0, 8).reduce((sum, movie) => sum + movie.sum_box_desc, 0)
  return (top8Sum / totalBoxOffice.value) * 100
}

const getTopMovieShare = () => {
  if (!topMovie.value || !totalBoxOffice.value) return 0
  return (topMovie.value.sum_box_desc / totalBoxOffice.value) * 100
}

const getMarketCompetition = () => {
  const top8Share = getTop8Proportion()
  if (top8Share > 80) return '集中度较高，市场竞争较为激烈'
  if (top8Share > 60) return '较为均衡，市场竞争适度'
  return '分散度高，市场竞争充分'
}

const getSplitRateComment = () => {
  if (avgSplitRate.value >= 0.7) return '整体分账比例较高，影片质量较好'
  if (avgSplitRate.value >= 0.5) return '整体分账比例适中，市场表现正常'
  return '整体分账比例偏低，需要提高影片质量'
}

// 计算分页后的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return tableData.value.slice(start, end)
})

// 格式化数字
const formatNumber = (num) => {
  return Number(num).toLocaleString('zh-CN', { maximumFractionDigits: 2 })
}

// 获取进度条颜色
const getProgressColor = (value) => {
  if (value >= 0.8) return '#67C23A'
  if (value >= 0.6) return '#409EFF'
  if (value >= 0.4) return '#E6A23C'
  return '#F56C6C'
}

// 初始化图表
const initChart = () => {
  if (chart.value) {
    chart.value.dispose()
  }
  chart.value = echarts.init(chartRef.value)
}

// 加载数据
const loadData = async () => {
  try {
    console.log('开始加载票房数据...')
    const response = await getMovies()
    console.log('API响应数据:', response)

    if (response?.status === 'success' && response?.data) {
      // 处理电影列表数据
      tableData.value = response.data.map(movie => ({
        ...movie,
        sum_box_desc: parseFloat(movie.sum_box_desc.replace(/[^0-9.]/g, '')) || 0,
        split_box_rate: parseFloat(movie.split_box_rate.replace('%', '')) / 100 || 0,
        release_info: movie.release_info || '-',
        updated_at: movie.updated_at || '-'
      })).sort((a, b) => b.sum_box_desc - a.sum_box_desc) // 按票房降序排序

      updateChart()
      ElMessage.success('数据加载成功')
    } else {
      console.warn('未获取到有效数据:', response)
      ElMessage.warning('未获取到数据')
      tableData.value = []
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，请检查网络连接')
    tableData.value = []
  }
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 更新图表
const updateChart = () => {
  if (!chart.value || !tableData.value.length) return
  
  let option = {
    title: {
      text: '电影票房分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        if (analysisType.value === 'proportion') {
          return `${params[0].name}<br/>${params[0].value.toLocaleString()}万 (${params[0].percent}%)`
        }
        return params.map(param => {
          const value = analysisType.value === 'split' 
            ? param.value.toFixed(2) + '%'
            : param.value.toLocaleString() + (param.seriesName.includes('票房') ? '万' : '')
          return `${param.seriesName}: ${value}`
        }).join('<br/>')
      }
    },
    legend: {
      top: 30
    },
    grid: {
      top: 80,
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    }
  }

  switch (analysisType.value) {
    case 'rank':
      option = {
        ...option,
        xAxis: {
          type: 'category',
          data: tableData.value.slice(0, 10).map(item => item.movie_name),
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: '票房(万)',
          axisLabel: {
            formatter: value => value.toLocaleString()
          }
        },
        series: [{
          name: '累计票房',
          type: 'bar',
          data: tableData.value.slice(0, 10).map(item => item.sum_box_desc),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#2378f7' },
                { offset: 0.7, color: '#2378f7' },
                { offset: 1, color: '#83bff6' }
              ])
            }
          },
          label: {
            show: true,
            position: 'top',
            formatter: value => value.value.toLocaleString() + '万'
          }
        }]
      }
      break

    case 'trend':
      option = {
        ...option,
        xAxis: {
          type: 'time',
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          name: '票房(万)',
          axisLabel: {
            formatter: value => value.toLocaleString()
          }
        },
        series: [{
          name: '票房趋势',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          data: tableData.value.map(item => [item.updated_at, item.sum_box_desc]),
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(58,77,233,0.3)' },
              { offset: 1, color: 'rgba(58,77,233,0.1)' }
            ])
          },
          itemStyle: {
            color: '#3a4de9'
          },
          lineStyle: {
            width: 3
          }
        }]
      }
      break

    case 'proportion':
      option = {
        ...option,
        tooltip: {
          trigger: 'item',
          formatter: '{b}<br/>票房：{c}万<br/>占比：{d}%'
        },
        series: [{
          name: '票房占比',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '60%'],
          data: tableData.value.slice(0, 8).map(item => ({
            name: item.movie_name,
            value: item.sum_box_desc
          })),
          label: {
            show: true,
            formatter: '{b}: {d}%'
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      break

    case 'split':
      option = {
        ...option,
        xAxis: {
          type: 'category',
          data: tableData.value.slice(0, 10).map(item => item.movie_name),
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: '分账比例(%)',
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [{
          name: '分账比例',
          type: 'bar',
          data: tableData.value.slice(0, 10).map(item => (item.split_box_rate * 100)),
          itemStyle: {
            color: params => {
              const value = params.value / 100
              return getProgressColor(value)
            }
          },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}%'
          }
        }]
      }
      break
  }
  
  chart.value.setOption(option)
}

// 监听分析类型变化
watch(analysisType, () => {
  updateChart()
})

// 监听窗口大小变化
window.addEventListener('resize', () => {
  chart.value?.resize()
})

onMounted(() => {
  initChart()
  loadData()
})
</script>

<style scoped>
.box-office-analysis {
  padding: 20px;
}

.analysis-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-right {
  display: flex;
  gap: 16px;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 500px;
  margin-top: 20px;
}

.analysis-summary {
  margin: 20px 0;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.analysis-summary h3 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
}

.summary-content {
  color: #606266;
}

.summary-content p {
  margin: 0 0 12px 0;
  font-weight: 500;
}

.summary-content ul {
  margin: 0;
  padding-left: 20px;
}

.summary-content li {
  margin: 8px 0;
  line-height: 1.5;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-progress) {
  margin-right: 0;
  width: 90%;
}

:deep(.el-table .cell) {
  padding: 8px;
}
</style>